package utils

import (
	"bytes"
	"crypto/aes"
	"encoding/base64"
	"errors"
	"fmt"
)

// 16   24   32  字节  盐
var key string = "edfg1674zxcq5963"

// 填充密码长度
func PadPwd(src_byte []byte, block_size int) []byte {
	// 16   block_size = 13
	//  13 - 3 = 10
	pad_num := block_size - len(src_byte)%block_size

	ret := bytes.Repeat([]byte{byte(pad_num)}, pad_num)
	//fmt.Println("this is PadPwd:=====================")
	//fmt.Println(ret)
	src_byte = append(src_byte, ret...)
	return src_byte
}

func AesEncoding(src string) string {
	src_byte := []byte(src)

	key_byte := []byte(key)
	block, err := aes.NewCipher(key_byte)
	//fmt.Println(block.BlockSize())
	//密码填充
	new_src_byte := PadPwd(src_byte, block.BlockSize())

	//fmt.Println(block)
	//fmt.Println(src_byte)
	fmt.Println(err)
	dst := make([]byte, len(new_src_byte))
	block.Encrypt(dst, new_src_byte)
	//fmt.Println(dst)

	// base64编码
	pwd := base64.StdEncoding.EncodeToString(dst)
	fmt.Printf("This is pwd: ")
	fmt.Println(pwd)
	return pwd
}

// aes解密
func AesDecoding(pwd string) (string, error) {
	fmt.Println("================")
	pwd_byte := []byte(pwd)
	fmt.Println(pwd_byte)
	pwd_byte, err := base64.StdEncoding.DecodeString(pwd)
	if err != nil {
		return pwd, err
	}

	key_byte := []byte(key)
	block, err_block := aes.NewCipher(key_byte)

	if err_block != nil {
		return pwd, err_block
	}
	// 填充去掉
	dst := make([]byte, len(pwd_byte))
	block.Decrypt(dst, pwd_byte)
	//fmt.Println(dst)
	dst, _ = UnPadPwd(dst)
	//fmt.Println(dst)
	return string(dst), nil
}

func UnPadPwd(dst []byte) ([]byte, error) {
	if len(dst) <= 0 {
		return dst, errors.New("长度有误！")
	}
	// 去掉的长度
	unpad_num := int(dst[len(dst)-1])
	return dst[:(len(dst) - unpad_num)], nil

}
